package com.example.casper.Experiment2024.items;

import android.content.Context;
import android.util.Log;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class locationSave {
    private final Context context;
    private final String data_file_name = "items.data";
    private final String share_data_file_name = "share_items.data"; // 新的数据文件名

    public locationSave(Context context) {
        this.context = context;
    }

    // 读取保存的Location列表（原始数据文件）
    public List<Location> readItems() {
        return readItems(data_file_name);
    }

    // 读取保存的Location列表（分享数据文件）
    public List<Location> readShareItems() {
        return readItems(share_data_file_name);
    }

    // 保存Location列表到文件（原始数据文件）
    public void saveGoneItems(List<Location> items) {
        saveItems(items, data_file_name);
    }

    // 保存Location列表到文件（分享数据文件）
    public void saveShareItems(List<Location> items) {
        saveItems(items, share_data_file_name);
    }

    // 读取数据的通用方法
    private List<Location> readItems(String fileName) {
        List<Location> items = new ArrayList<>();
        File file = new File(context.getFilesDir(), fileName);

        try {
            if (file.exists()) {
                FileInputStream fileIn = new FileInputStream(file);
                ObjectInputStream in = new ObjectInputStream(fileIn);
                items = (List<Location>) in.readObject();
                in.close();
                fileIn.close();
            }
        } catch (IOException | ClassNotFoundException e) {
            Log.e("Experiment2024.data", "Error reading data: " + e.toString());
        }
        return items;
    }

     //保存数据的通用方法
    private void saveItems(List<Location> items, String fileName) {
        try {
            File filesDir = context.getFilesDir();
            if (!filesDir.exists()) {
                filesDir.mkdirs();
            }

            File file = new File(filesDir, fileName);
            FileOutputStream fileOut = new FileOutputStream(file);
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(items);
            out.close();
            fileOut.close();
        } catch (IOException e) {
            Log.e("Experiment2024.data", "Error saving data: " + e.toString());
        }
    }
}